#!/bin/bash
[% c("var/set_default_env") -%]
[% pc('go', 'var/setup', { go_tarfile => c('input_files_by_name/go') }) %]
[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
[% IF c("var/linux") %]
  tar -C /var/tmp/dist -xf $rootdir/[% c('input_files_by_name/binutils') %]
  export PATH="/var/tmp/dist/binutils/bin:$PATH"
[% END -%]
distdir=/var/tmp/dist/[% project %]
[% c("var/set_PTDIR_DOCSDIR") -%]
mkdir -p $PTDIR $DOCSDIR
[% IF c("var/osx") %]
  export CGO_ENABLED=1
  export CGO_CFLAGS="[% c("var/FLAGS") %] -mmacosx-version-min=10.7"
  export CGO_CXXFLAGS="[% c("var/FLAGS") %] -stdlib=libc++ -mmacosx-version-min=10.7"
  export CGO_LDFLAGS="[% c("var/FLAGS") %] -stdlib=libc++ -mmacosx-version-min=10.7"
  export CC="$clangdir/bin/clang"
  export CXX="$clangdir/bin/clang++"
[% END %]

tar -C /var/tmp/dist -xf [% c('input_files_by_name/go-webrtc') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/uniuri') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/goptlib') %]

mkdir -p /var/tmp/build
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz
cd /var/tmp/build/[% project %]-[% c('version') %]

cd client
[% IF c("var/osx") -%]
  # Without faketime, snowflake-client would contain the timestamp of the
  # temporary client.a file created during "go build".
  [% c("var/faketime") %] go build -ldflags '-s'
[% ELSE -%]
  go build -ldflags '-s'
[% END -%]
[% IF c("var/osx") -%]
  # Hack: Overwrite variable absolute paths embedded in the binary. clang 3.8.0
  # on Darwin embeds such paths and the issue is unsolved in upstream Go as of
  # 2016-06-28:
  # https://github.com/golang/go/issues/9206#issuecomment-310476743
  # The two kinds of paths are ("000000000" stands for 9 random digits):
  #   /tmp/go-build000000000
  #   /tmp/go-link-000000000
  # Such paths are the output of ioutil.TempDir("", "go-build") and
  # ioutil.TempDir("", "go-link-").
  cp -a client client.stomped
  sed -i -E -e 's#(/tmp/go-build|/tmp/go-link-)[0-9]{9}/#\1XXXXXXXXX/#g' client.stomped
  # Sanity check: make sure the file actually changed. If it did not, it could
  # mean that a change in go or clang has made this step unnecessary.
  if cmp client client.stomped
  then
    echo "No paths replaced in snowflake-client. Maybe the replacement failed or is no longer needed."
    echo "Check projects/snowflake/build"
    exit 1
  fi
  mv -f client.stomped client
[% END -%]
cp -a client[% IF c("var/windows") %].exe[% END %] $PTDIR/snowflake-client[% IF c("var/windows") %].exe[% END %]

cd ..
cp -a README.md LICENSE $DOCSDIR

cd $distdir
[% c('tar', {
        tar_src => [ '.' ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
